package com.mastercard

import com.mastercard.Transaction

class DemoController {
	/*
	 * DemoController will:
	 * 1) Accept the request params
	 * 2) Create a real transaction and save to DB
	 * 3) Check with predefined budget
	 * 4) Send predefined SMS
	 */
	def sendSMS(String message) {
		String url = "http://137.132.247.154:8888/SMS/send.aspx?rep=86132470&msg="
		message = URLEncoder.encode(message, "UTF-8")
		url = url + message
		
		URL oracle = new URL(url);
		BufferedReader reader = new BufferedReader(
		new InputStreamReader(oracle.openStream()));

		String inputLine;
		while ((inputLine = reader.readLine()) != null)
			println(inputLine);
		reader.close();
	}
	
    def index() { 
		render(text:"hello world")
		
		// Accept request params and save to DB
		CreditCard card = new CreditCard()
		card.number = params.get('number')
		card.nameOnCard = params.get('nameOnCard')
		card.save()
		
		println("card id: " + card.id)
		
		Transaction transaction = new Transaction()
		transaction.amount = Double.parseDouble(params.get('amount'))
		transaction.currency = params.get('currency')
		transaction.datetime = new Date()
		transaction.creditCard = card
		transaction.save()
		
		float totalAmount = 0
		for (Transaction t in Transaction.findAll()) {
			totalAmount += t.amount
		}
		
		
		// send SMS
		if (totalAmount > 100) {
			sendSMS("You exceeded \$100 August budget for  ****" + card.number.substring(12) + ". Total spending is " +
				totalAmount)
		}
		else {
			sendSMS("You almost reach your \$100 August budget for  " + card.number.substring(12) + ". Total spending is " +
				totalAmount)
		}
		
		render(text: "Success")
	}
}
